﻿
using System;
using System.Data;
using System.Data.Linq;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using System.Collections.Generic;
using CSM.Models;

namespace CSM.Controllers
{
    public class CSMAccount
    {
        private string lastError;//出错说明

        public string LastError
        {
            get { return lastError; }
            private set { lastError = value; }
        }
        private string currectOperator;//编辑人ID

        public string CurrectOperator
        {
            get { return currectOperator; }
            private set { currectOperator = value; }
        }

        private TCsm_JS_User currectRecord;

        public TCsm_JS_User CurrectRecord
        {
            get { return currectRecord; }
            private set { currectRecord = value; }
        }

        private CustomDataContext db = new CustomDataContext();

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="currectOperator">编辑人ID</param>
        public CSMAccount(string currectOperator)
        {
            if (string.IsNullOrEmpty(currectOperator))
                throw new Exception("无效编辑人！");
            if (db.TCsm_JS_User.Count(u => u.UserID == currectOperator) == 0)
                throw new Exception("没有此编辑人。无法生成ACCOUNT系列操作！");
            this.currectOperator = currectOperator;
            this.currectRecord = db.TCsm_JS_User.Where(u => u.UserID == currectOperator).Single();
        }

        public CSMAccount()
        {

        }

        /// <summary>
        /// 设置账户状态
        /// </summary>
        /// <param name="username">操作员ID</param>
        /// <param name="enable">是否激活?</param>
        /// <returns></returns>
        public int SetEnable(string username, bool enable)
        {
            if ((from u in db.TCsm_JS_User
                 where u.UserID == username
                 select u.UserID).Count() == 0)
            {
                lastError = "无此操作员ID";
                return -1;
            }
            var user = (from u in db.TCsm_JS_User
                        where u.UserID == username
                        select u).Single();
            RecordModifyTime(ref user);
            user.IsStop = !enable;
            db.SubmitChanges(ConflictMode.ContinueOnConflict);
            return 0;
        }

        public int SetDisable(string username, bool disable)
        {
            return SetEnable(username, !disable);
        }

        /// <summary>
        /// 删除账户
        /// </summary>
        /// <param name="username">操作员ID</param>
        /// <returns></returns>
        public int Delete(string username)
        {
            if ((from u in db.TCsm_JS_User
                 where u.UserID == username
                 select u.UserID).Count() == 0)
            {
                lastError = "无此操作员ID";
                return -1;
            }
            var user = (from u in db.TCsm_JS_User
                        where u.UserID == username
                        select u).Single();
            db.TCsm_JS_User.DeleteOnSubmit(user);
            db.SubmitChanges(ConflictMode.ContinueOnConflict);
            return 0;
        }



        /// <summary>
        /// 创建账户
        /// </summary>
        /// <param name="username">操作员ID</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public int Create(string username, string realname, string password, string companyID, string dutyPartID)
        {
            TCsm_JS_User user = new TCsm_JS_User();
            user.CreateTime = DateTime.Now;
            //user.公司ID = companyID;
            user.Password = EncryptPassword(password);
            user.IsStop = false;
            //user.责任部门ID = Convert.ToInt32(dutyPartID);
            user.UserID = username;
            user.UserName = realname;
            user.UserRightID = "0";
            user.RoleID = "0";
            RecordModifyTime(ref user);
            db.TCsm_JS_User.InsertOnSubmit(user);
            try
            {
                db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            }
            catch (Exception e)
            {
                lastError = e.Message;
                return -1;
            }
            return 0;
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="username">操作员ID</param>
        /// <param name="oldpassword">旧密码</param>
        /// <param name="password">新密码</param>
        /// <returns></returns>
        public int ModifyPassword(string username, string oldpassword, string password)
        {
            if ((from u in db.TCsm_JS_User
                 where u.UserID == username && u.Password == EncryptPassword(oldpassword)
                 select u.UserID).Count() == 0)
            {
                lastError = "没有该操作员或者密码错误";
                return -1;
            }
            var user = (from u in db.TCsm_JS_User
                        where u.UserID == username && u.Password == EncryptPassword(oldpassword)
                        select u).Single();
            user.Password = EncryptPassword(password);
            db.SubmitChanges(ConflictMode.ContinueOnConflict);
            return 0;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="username">操作员ID</param>
        /// <param name="oldpassword">旧密码</param>
        /// <param name="password">新密码</param>
        /// <returns></returns>
        public int ResetPassword(string username, string password)
        {
            if ((from u in db.TCsm_JS_User
                 where u.UserID == username
                 select u.UserID).Count() == 0)
            {
                lastError = "没有该操作员";
                return -1;
            }
            var user = (from u in db.TCsm_JS_User
                        where u.UserID == username
                        select u).Single();
            user.Password = EncryptPassword(password);
            RecordModifyTime(ref user);
            db.SubmitChanges(ConflictMode.ContinueOnConflict);
            return 0;
        }


        /// <summary>
        /// 不可逆HASH密码
        /// </summary>
        /// <param name="passwordString"></param>
        /// <returns></returns>
        static public string EncryptPassword(string passwordString)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(passwordString, "MD5");
        }

        /// <summary>
        /// 设置操作员角色
        /// </summary>
        /// <param name="operatorID">操作员ID</param>
        /// <param name="roles">操作员角色组</param>
        /// <returns></returns>
        public int SetUserToRoles(string operatorID, string[] roles)
        {
            string rolesString = string.Join(",", roles);
            return SetUserToRoles(operatorID, rolesString);
        }

        /// <summary>
        /// 设置操作员角色
        /// </summary>
        /// <param name="operatorID">操作员ID</param>
        /// <param name="rolesString">操作员角色组</param>
        /// <returns></returns>
        public int SetUserToRoles(string operatorID, string rolesString)
        {
            if (db.TCsm_JS_User.Count(a => a.UserID == operatorID) == 0)
            {
                lastError = "没有这个操作员!";
                return -1;
            }
            var user = (from a in db.TCsm_JS_User
                        where a.UserID == operatorID
                        select a).Single();
            RecordModifyTime(ref user);
            user.RoleID = rolesString;
            db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            return 0;
        }


        /// <summary>
        /// 设置操作员权限
        /// </summary>
        /// <param name="operatorID">操作员ID</param>
        /// <param name="auths">操作员权限</param>
        /// <returns></returns>
        public int SetUserToAuths(string operatorID, string[] auths)
        {
            string authsString = string.Join(",", auths);
            return SetUserToAuths(operatorID, authsString);
        }


        /// <summary>
        /// 设置操作员权限
        /// </summary>
        /// <param name="operatorID">操作员ID</param>
        /// <param name="authsString">操作员权限</param>
        /// <returns></returns>
        public int SetUserToAuths(string operatorID, string authsString)
        {
            if (db.TCsm_JS_User.Count(a => a.UserID == operatorID) == 0)
            {
                lastError = "没有这个操作员!";
                return -1;
            }
            var user = (from a in db.TCsm_JS_User
                        where a.UserID == operatorID
                        select a).Single();
            user.UserRightID = authsString;
            RecordModifyTime(ref user);
            db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            return 0;
        }

        /// <summary>
        /// 录入编辑人信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private int RecordModifyTime(ref TCsm_JS_User user)
        {
            if (string.IsNullOrEmpty(currectOperator))
                throw new Exception("该操作需要指定编辑人.但当前编辑人为空!请提交该BUG并附操作过程.");
            user.ModityID = currectOperator;
            user.ModifyTime = DateTime.Now;
            return 0;
        }



        /// <summary>
        /// 返回所有用户
        /// </summary>
        /// <returns></returns>
        public IEnumerable<TCsm_JS_User> GetUsers()
        {
            var users = (from u in db.TCsm_JS_User
                         select u);
            return users;
        }


        /// <summary>
        /// 返回模糊查询的操作员
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns></returns>
        public IEnumerable<TCsm_JS_User> GetUsers(string username)
        {
            var users = (from u in db.TCsm_JS_User
                         where u.UserID.Contains(username)
                         select u);
            return users;
        }

        /// <summary>
        /// 返回所属的作业中心
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns></returns>
        //public int GetCostCenterID(string username)
        //{
        //    return Convert.ToInt32((from c in db.TCsm_JS_User
        //            where c. == username
        //            select c.责任部门ID).Single());
        //}

        /// <summary>
        /// 返回所属的作业中心
        /// </summary>
        /// <returns></returns>
        //public int GetCostCenterID()
        //{
        //    return GetCostCenterID(currectOperator);
        //}

    }
}
